using Microsoft.AspNetCore.Mvc;
using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;

namespace SG3L_RAG.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class LogsController : ControllerBase
    {
        private readonly ILogService _logService;

        public LogsController(ILogService logService)
        {
            _logService = logService;
        }

        /// <summary>
        /// 获取所有日志
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Log>>> GetAllLogs()
        {
            var logs = await _logService.GetAllAsync();
            return Ok(logs);
        }

        /// <summary>
        /// 根据ID获取日志
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<Log>> GetLog(Guid id)
        {
            var log = await _logService.GetByIdAsync(id);
            if (log == null)
            {
                return NotFound($"日志 {id} 不存在");
            }
            return Ok(log);
        }

        /// <summary>
        /// 根据类型获取日志列表
        /// </summary>
        [HttpGet("type/{type}")]
        public async Task<ActionResult<IEnumerable<Log>>> GetLogsByType(string type)
        {
            var logs = await _logService.GetByTypeAsync(type);
            return Ok(logs);
        }

        /// <summary>
        /// 根据日期范围获取日志列表
        /// </summary>
        [HttpGet("date-range")]
        public async Task<ActionResult<IEnumerable<Log>>> GetLogsByDateRange(
            [FromQuery] DateTime startDate, 
            [FromQuery] DateTime endDate)
        {
            var logs = await _logService.GetByDateRangeAsync(startDate, endDate);
            return Ok(logs);
        }

        /// <summary>
        /// 获取最近的日志列表
        /// </summary>
        [HttpGet("recent")]
        public async Task<ActionResult<IEnumerable<Log>>> GetRecentLogs([FromQuery] int count = 100)
        {
            var logs = await _logService.GetRecentLogsAsync(count);
            return Ok(logs);
        }

        /// <summary>
        /// 获取错误日志
        /// </summary>
        [HttpGet("errors")]
        public async Task<ActionResult<IEnumerable<Log>>> GetErrorLogs()
        {
            var logs = await _logService.GetErrorLogsAsync();
            return Ok(logs);
        }

        /// <summary>
        /// 获取警告日志
        /// </summary>
        [HttpGet("warnings")]
        public async Task<ActionResult<IEnumerable<Log>>> GetWarningLogs()
        {
            var logs = await _logService.GetWarningLogsAsync();
            return Ok(logs);
        }

        /// <summary>
        /// 获取信息日志
        /// </summary>
        [HttpGet("info")]
        public async Task<ActionResult<IEnumerable<Log>>> GetInfoLogs()
        {
            var logs = await _logService.GetInfoLogsAsync();
            return Ok(logs);
        }

        /// <summary>
        /// 创建新日志
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<Log>> CreateLog([FromBody] CreateLogRequest request)
        {
            try
            {
                var log = await _logService.CreateAsync(request.Type, request.Content, request.ExceptionDetail);
                return CreatedAtAction(nameof(GetLog), new { id = log.Id }, log);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建日志失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新日志
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateLog(Guid id, [FromBody] Log log)
        {
            if (id != log.Id)
            {
                return BadRequest("日志ID不匹配");
            }

            try
            {
                await _logService.UpdateAsync(log);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"更新日志失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除日志
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteLog(Guid id)
        {
            try
            {
                await _logService.DeleteAsync(id);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"删除日志失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 记录信息日志
        /// </summary>
        [HttpPost("info")]
        public async Task<IActionResult> LogInfo([FromBody] SimpleLogRequest request)
        {
            try
            {
                await _logService.LogInfoAsync(request.Content);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"记录信息日志失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 记录警告日志
        /// </summary>
        [HttpPost("warning")]
        public async Task<IActionResult> LogWarning([FromBody] SimpleLogRequest request)
        {
            try
            {
                await _logService.LogWarningAsync(request.Content);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"记录警告日志失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 记录错误日志
        /// </summary>
        [HttpPost("error")]
        public async Task<IActionResult> LogError([FromBody] ErrorLogRequest request)
        {
            try
            {
                await _logService.LogErrorAsync(request.Content, request.ExceptionDetail);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"记录错误日志失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 清理旧日志
        /// </summary>
        [HttpDelete("cleanup")]
        public async Task<IActionResult> CleanupOldLogs([FromQuery] DateTime beforeDate)
        {
            try
            {
                await _logService.CleanupOldLogsAsync(beforeDate);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"清理日志失败: {ex.Message}");
            }
        }
    }

    // 请求模型
    public class CreateLogRequest
    {
        public string Type { get; set; } = string.Empty;
        public string Content { get; set; } = string.Empty;
        public string? ExceptionDetail { get; set; }
    }

    public class SimpleLogRequest
    {
        public string Content { get; set; } = string.Empty;
    }

    public class ErrorLogRequest
    {
        public string Content { get; set; } = string.Empty;
        public string? ExceptionDetail { get; set; }
    }
}
